<template>
  <div class="hospitalList padding_20">
    <el-input v-model="hospitalName"
              placeholder="请输入医院名称"
              class="w-200"
              clearable
              @clear="handleQuery"/>
    <el-select v-model="company"
               ref="selectDom"
               placeholder="请选择公司名称"
               filterable
               remote
               reserve-keyword
               :remote-method="searchMethod"
               :loading="loading1"
               class="w-200"
               clearable
               @clear="handleQuery"
               @change="handleSelect">
      <el-option v-for="item in companyFilterList"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id">
      </el-option>
    </el-select>
    <el-button type="primary"
               @click="handleQuery">查 询
    </el-button>
    <el-button type="primary"
               @click="handleOption(null, null, 'add')">新 增
    </el-button>
    <!--医院列表-->
    <Table border
           :columns="titles"
           :data="dataList"
           stripe
           class="mt-20">
      <template slot-scope="{row,index}"
                slot="action">
        <!-- {{row}} -->
        <span @click="handleOption(index, row, 'edit')">编辑</span>
        <span @click="setPharmacist(index)">医院药师设置</span>
        <span @click="handleOption(index, row, 'set')">设置</span>
        <span @click="handleOption(index, row, 'del')">删除</span>
        <span @click="handleOption(index,row, 'branch')">分院配置</span>
      </template>
    </Table>
    <!--分页-->
    <Page :current.sync="currentPage"
          :total="totals"
          :page-size="pageSize"
          @on-change="handleChange"
          show-total/>
    <el-dialog title="头像"
               center
               :visible.sync="imageModal"
               width="30%">
      <img :src="imageUrl"
           style="width:100%;height:100%">
      <span slot="footer">
        <el-button type="primary"
                   @click="imageModal = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 医院药师设置 -->
    <Modal v-model="editPharmacistPage"
           width="90%"
           title="医院药师设置"
           @on-ok="saveData">
      <div class="pd-20">
        <Table border
               :columns="doctorTitle"
               :data="pharmacistList">
          <template slot-scope="{row,index}"
                    slot="action">
            <span @click="deleteHospitalPharmacist(index)">删除</span>
          </template>
        </Table>
        <div class="mt-20">
          <el-input v-model="doctorName"
                    placeholder="请输入医生名称"
                    clearable
                    @clear="queryHospitalDoctor"
                    class="w-200"/>
          <el-button type="primary"
                     @click="queryHospitalDoctor">查 询
          </el-button>
        </div>
        <Table border
               :columns="doctorTitle"
               :data="doctorList"
               class="mt-20">
          <template slot-scope="{row,index}"
                    slot="action">
            <span @click="setHospitalPharmacist(index)"
                  style="font-size: 20px;color: #00A539">
              <Icon type="ios-build"/>
            </span>
          </template>
        </Table>
        <Page :current.sync="dcurrentPage"
              :total="dtotals"
              :page-size="dpageSize"
              @on-change="changeHospitalDoctor"
              show-total/>
      </div>
    </Modal>
    <!-- 医院就诊卡密码配置 -->
    <Modal v-model="visitCardCmdModal"
           title="医院就诊卡密码配置"
           @on-ok="saveVisitCardConfig">
      <div class="pd-20">
        <el-input v-model="visitCardConfig"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入就诊卡密码"/>
      </div>
    </Modal>
    <branch v-if="showdialog"
            :dialogData='dialogData'
            @closedialog='showdialog=false'/>
    <edit-dialog v-if="showEditDialog" :visible.sync="showEditDialog" :dataObj="dataObj"/>
  </div>
</template>

<script>
import branch from './branchHospital/table'
import editHospitalDialog from "./editHospitalDialog";

export default {
  name: "hospitalList",
  data() {
    let vm = this;
    return {
      title: '新增医院',
      showdialog: false,
      showEditDialog: false,
      dataObj: {},
      loading1: false,
      loading2: false,
      dialogData: {},
      fileMaxSize: 1024 * 50,
      fileUploadAction: null,
      hospitalName: null,
      doctorName: null,
      currentPage: 1,
      dcurrentPage: 1,
      dtotals: 0,
      dpageSize: 10,
      imageModal: false,
      dialogVisible: false,
      editPharmacistPage: false,
      deleteIndex: null,
      visitCardCmdModal: false,
      imageUrl: null,
      totals: 0,
      pageIndex: 1,
      pageSize: 20,
      visitCardConfig: null,
      currentHospitalId: null,
      currentHospitalIndex: null,
      hospitalList: [],
      pharmacistList: [],
      doctorList: [],


      hospitalLevelList: [],
      hospitalPropertyList: [
        {
          "id": 1,
          "name": "综合医院"
        },
        {
          "id": 2,
          "name": "专科医院"
        }
      ],
      titles: [
        {
          title: '头像',
          key: 'imageUrl',
          width: 95,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.imageUrl
                },
                style: {
                  width: '60px',
                  height: '60px',
                  'border-radius': '50%'
                },
                on: {
                  click: (event) => {
                    vm.showBigImage(params.row.imageUrl);
                  }
                }
              }),
            ]);
          }
        },
        {
          title: '医院名称 ',
          key: 'name',
          render: (h, params) => {
            return h('div', [
              h("div", [h('span', params.row.name)]),
            ]);
          }
        },
        {
          title: '排序号 ',
          key: 'sortNum',
          align: 'center',
          width: 80,
        },
        {
          title: '是否开通 ',
          key: 'openStatus',
          width: 100,
          render: (h, params) => {
            if (params.row.openStatus == 0) {
              return h('div', [
                h("div", [h('span', {
                  style: {
                    color: '#E93027'
                  }
                }, "未开通")]),
              ]);
            } else if (params.row.openStatus == 1) {
              return h('div', [
                h("div", [h('span', {
                  style: {
                    color: '#2CB044'
                  }
                }, "已开通")]),
              ]);
            }
          }
        },
        {
          title: '中心',
          key: 'hospitalCenterName',
        },
        {
          title: '所属公司',
          key: 'companyName',
        },
        {
          title: '地址 ',
          key: 'address',
        },
        {
          title: '电话 ',
          key: 'phone',
        },
        {
          title: '介绍 ',
          key: 'introduce',
          render: (h, params) => {
            if (params.row.introduce) {
              if (params.row.introduce.length > 50) {
                let text = params.row.introduce.substr(0, 47);
                return h('div', [
                  h("div", [h('span', text + "...")]),
                ]);
              }
            }
          }
        },
        {
          title: '创建时间',
          key: 'createTime',
          width: 150,
          render: (h, params) => {
            return h('span',
              this.commonFunction.timestampFormat(new Date(params.row.createTime), 'yyyy-MM-dd hh:mm'));
          }
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          width: 120
        }
      ],
      doctorTitle: [
        {
          title: '头像',
          key: 'headImageUrl',
          width: 95,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.headImageUrl
                },
                style: {
                  width: '60px',
                  height: '60px',
                  'border-radius': '50%'
                },
                on: {
                  click: (event) => {
                    vm.showBigImage(params.row.headImageUrl);
                  }
                }
              }),
            ]);
          }
        },
        {
          title: '医生 ',
          key: 'nickName',
          render: (h, params) => {
            if (!params.row.nickName) {
              params.row.nickName = "";
            }
            if (!params.row.positionName) {
              params.row.positionName = "";
            }
            return h('div', [
              h("div", [h('span', '登录名：' + params.row.loginName)]),
              h("div", [h('span', '昵称：' + params.row.nickName), h('span', "  (" + params.row.positionName + ")"),])
            ]);
          }
        }, {
          title: '专家 ',
          key: 'isExpert',
          width: 90,
          render: (h, params) => {
            if (params.row.isExpert === 0) {
              return h('div', [h('span', {
                style: {
                  color: '#3B3E40'
                }
              }, '非专家')]);
            } else if (params.row.isExpert === 1) {
              return h('div', [h('span', {
                style: {
                  color: '#FFA949'
                }
              }, '三甲专家')]);
            } else if (params.row.isExpert === 2) {
              return h('div', [h('span', {
                style: {
                  color: '#2CB044'
                }
              }, '专科专家')]);
            }
          }
        },
        {
          title: '性别 ',
          key: 'sex',
          width: 70,
          render: (h, params) => {
            if (params.row.sex === 0) {
              return h('div', [h('span', '女')]);
            } else if (params.row.sex === 1) {
              return h('div', [h('span', '男')]);
            }
          }
        },
        {
          title: '医院&科室',
          key: 'hospitalName',
          render: (h, params) => {
            if (params.row.hospitalName) {
              return h('div', [
                h("div", [h('span', params.row.hospitalName)]),
                h("div", [h('span', '(' + params.row.departmentName + ')')])
              ]);
            } else {
              return h('div', [
                h('div', ""),
              ]);
            }
          }
        },
        {
          title: '审核状态',
          key: 'isAuth',
          width: 100,
          render: (h, params) => {
            if (params.row.isAuth == 0) {
              return h('div', [
                h("span", {
                  style: {
                    color: '#3B3E40'
                  }
                }, "待提交"),
              ]);
            } else if (params.row.isAuth == 1) {
              return h('div', [
                h('span', {
                  style: {
                    color: '#005DF3'
                  }
                }, "待审核"),
              ]);
            } else if (params.row.isAuth == 2) {
              return h('div', [
                h('span', {
                  style: {
                    color: '#2CB044'
                  }
                }, "通过"),
              ]);
            } else if (params.row.isAuth == -1) {
              return h('div', [
                h('span', {
                  style: {
                    color: '#BB0000'
                  }
                }, "驳回"),
              ]);
            }
          }
        },
        {
          title: '简介',
          key: 'introduce'
        },
        {
          title: '创建时间',
          key: 'createTime',
          width: 150,
          render: (h, params) => {
            return h('span',
              this.commonFunction.timestampFormat(new Date(params.row.createTime), 'yyyy-MM-dd hh:mm'));
          }
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          width: 120
        }
      ],
      dataList: [],
      provinceList: [],
      cityList: [],
      districtList: [],
      company: '',
      companyList: [],
      companyFilterList: [],
      companyList2: [],
      companyFilterList2: [],

    }
  },
  components: {
    branch,
    'edit-dialog': editHospitalDialog
  },
  created() {
    this.fileUploadAction = this.api.file.upload;
    this.initTableData();
    this.selectChildren1(0);
  },
  methods: {

    handleQuery() {
      this.pageIndex = 1
      this.initTableData()
    },
    initTableData() {
      let param = {
        name: this.hospitalName,
        company: this.company,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex - 1
      };
      this.post(this.api.hospitalManager.list, param).then((res) => {
        if (res.data.code === '200') {
          this.dataList = res.data.object;
          this.totals = res.data.totalNum;
        }
      });


    },
    handleChange(page) {
      this.pageIndex = page;
      this.initTableData();
    },
    showBigImage(url) {
      this.imageUrl = url;
      this.imageModal = true;
    },


    cancelBtn() {
      this.dialogVisible = false;
      this.$refs.formRefs.resetFields();
    },
    // 回显
    handleOption(index, row, op) {
      switch (op) {
        case 'add':

          this.showEditDialog = true
          this.dataObj = {}
          break;
        case 'edit':
          this.showEditDialog = true
          this.dataObj = {id: row.id}

          break;
        case 'set':
          let dto = this.dataList[index];
          this.currentHospitalId = dto.id;
          this.visitCardCmdModal = true;
          this.visitCardConfig = dto.visitCardConfig;
          break;
        case 'del':
          this.deleteIndex = index;
          this.$confirm('确认删除该医院？')
            .then(_ => {
              let obj = this.dataList[this.deleteIndex];
              if (obj) {
                this.post(this.api.hospitalManager.deleteHospital, {"id": obj.id}).then((res) => {
                  if (res.data.code === '200') {
                    this.$message.success("删除成功!");
                    this.initTableData();
                  }
                });
              }
            })
            .catch(_ => {
            });
          break;
        case 'branch':
          this.showdialog = true;
          this.dialogData = {
            show: true,
            info: row,
            title: '分院列表'
          }
          break;
      }
    },

    saveData() {
    },
    submitForm() {
      this.$refs.formRefs.validate((valid) => {
        if (valid) {
          this.post(this.api.hospitalManager.saveHospital, this.hospitalDetail).then((res) => {
            if (res.data.code === '200') {
              this.initTableData();
              this.$message.success("保存成功");
              this.dialogVisible = false;
            }
          })
        }
      })
    },
    // 医院药师
    initHospitalDoctor() {
      let param = {
        nickName: this.doctorName,
        pageSize: this.dpageSize,
        isAuth: 2,
        pageIndex: this.pageIndex - 1
      };
      this.post(this.api.doctorManager.list, param).then((res) => {
        if (res.data.code === '200') {
          this.doctorList = res.data.object;
          this.dtotals = res.data.totalNum;
        }
      });
    },
    queryHospitalDoctor() {
      this.pageIndex = 1;
      this.initHospitalDoctor();
    },
    changeHospitalDoctor(page) {
      this.pageIndex = page;
      this.initHospitalDoctor();
    },
    initHospitalPharmacist() {
      this.post(this.api.hospitalManager.selectHospitalPharmacist, {"id": this.currentHospitalId}).then((res) => {
        if (res.data.code === '200') {
          this.pharmacistList = res.data.object;
          this.editPharmacistPage = true;
        }
      });
    },
    setPharmacist(index) {
      this.currentHospitalId = this.dataList[index].id;
      this.currentHospitalIndex = index;
      this.initHospitalDoctor();
      this.initHospitalPharmacist();
    },

    saveVisitCardConfig() {
      if (!this.visitCardConfig) {
        this.$message.error("就诊卡密码配置为空");
      }
      if (!this.currentHospitalId) {
        this.$message.error("请选择医院");
      }
      let data = {
        id: this.currentHospitalId,
        visitCardConfig: this.visitCardConfig
      };
      this.post(this.api.hospitalManager.saveVisitCardConfig, data).then((res) => {
        this.visitCardConfig = "";
        this.currentHospitalId = null;
        if (res.data.code === '200') {
          this.$message.info("保存成功")
        }
      });
    },
    setHospitalPharmacist(index) {
      let doctorId = this.doctorList[index].id;
      let param = {
        "hospitalId": this.currentHospitalId,
        "doctorId": doctorId
      };
      this.post(this.api.hospitalManager.setHospitalPharmacist, param).then((res) => {
        if (res.data.code === '200') {
          this.setPharmacist(this.currentHospitalIndex);
        }
      });
    },

    deleteHospitalPharmacist(index) {
      let doctorId = this.pharmacistList[index].id;
      let param = {
        "hospitalId": this.currentHospitalId,
        "doctorId": doctorId
      };
      this.$confirm('确认删除？')
        .then(_ => {
          this.post(this.api.hospitalManager.deleteHospitalPharmacist, param).then((res) => {
            if (res.data.code === '200') {
              this.setPharmacist(this.currentHospitalIndex);
            }
          });
        })
        .catch(_ => {
        });

    },
    // 远程搜索参与公司
    searchMethod(query) {
      if (query !== '') {
        this.loading1 = true;
        let _this = this;
        this.post(this.api.company.companyList, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          name: query,
          hospitalType: '',
          status: 1
        }).then(res => {
          if (res.data.code === '200') {
            this.loading1 = false;
            _this.companyList = res.data.object;
          }
        })
        setTimeout(() => {
          this.loading1 = false;
          this.companyFilterList = this.companyList.filter(item => item.name.indexOf(query) > -1);
        }, 200)
      } else {
        this.companyFilterList = [];
      }
    },
    handleSelect(item) {
      this.company = item;
    },

    handleSelect2(item) {
      this.hospitalDetail.company = item;
      this.$forceUpdate()
    },
  }
}
</script>

<style scoped>
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
